package org.swift.commons.xml.vtd;

import java.util.HashMap;
import java.util.Map;

import com.ximpleware.NavException;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;

public class VTDUtil {
	public static Map<String, String> extractNamespaces(VTDNav nav) throws NavException {		
		int maxIndex = nav.getTokenCount();
		int index = -1;
		Map<String, String> map = new HashMap<String, String>();
		while(++index < maxIndex) {
			if (nav.getTokenType(index) == VTDNav.TOKEN_ATTR_NS) {
				String ns = nav.toString(index);	
				ns = ns.substring(ns.indexOf(':')+1);				
				String value = nav.toString(++index);
				map.put(ns, value);
			}			
		}
		return map;
	}
	
	public static Map<String, String> extractNamespaces(byte[] xml) {
		VTDGen gen = new VTDGen();
		gen.setDoc(xml);
		try {
			gen.parse(true);
			return VTDUtil.extractNamespaces(gen.getNav());
		} catch (Exception e) {
			throw new RuntimeException("Could not get namespaces from xml.", e);
		}
	}
}
